using B.S.ProcessEngine.Api.Dtos.ResponseDto;
using B.S.ReportEvent.ApiNew.Dtos.ResponseDto;
using Newtonsoft.Json;

namespace B.S.ReportEvent.ApiNew.Utils;

public class HttpHelper : IHttpHelper
{
    private readonly HttpClient _client;
    private readonly IConfiguration _configuration;
    private readonly ILogger<HttpHelper> _logger;

    public HttpHelper(IHttpClientFactory httpClientFactory, IConfiguration configuration, ILogger<HttpHelper> logger)
    {
        _configuration = configuration;
        _logger = logger;
        _client = httpClientFactory.CreateClient();
    }

    public async Task<GetFormNodesForInstanceResponseDto> GetFormNodesForInstance(int formId)
    {
        try
        {
            var uri = new Uri($"{_configuration["HttpClientSetting:ProcessCenter"]}/api/FormNode/GetFormNodesForInstance/{formId}");

            // 发出一个 GET 请求
            var response = await _client.GetAsync(uri);

            // 如果没有请求成功
            if (!response.IsSuccessStatusCode) return new GetFormNodesForInstanceResponseDto();

            // 读取响应内容
            var query = await response.Content.ReadAsStringAsync();

            // 将 JSON 字符串反序列化为对象
            var result = JsonConvert.DeserializeObject<GetFormNodesForInstanceResponseDto>(query);

            return result ?? new GetFormNodesForInstanceResponseDto();
        }
        catch (Exception e)
        {
            _logger.LogError(e, "获取表单节点失败");
            return new GetFormNodesForInstanceResponseDto();
        }
    }

    public async Task<GetFormNodeByFormNoResponseDto> GetFormNodeByFormNo(string formNo)
    {
        try
        {
            var uri = new Uri($"{_configuration["HttpClientSetting:ProcessCenter"]}/api/FormNode/GetFormNodeByFormNo/{formNo}");

            // 发出一个 GET 请求
            var response = await _client.GetAsync(uri);

            // 如果没有请求成功
            if (!response.IsSuccessStatusCode) return new GetFormNodeByFormNoResponseDto() { Suc = false };

            // 读取响应内容
            var query = await response.Content.ReadAsStringAsync();

            // 将 JSON 字符串反序列化为对象
            var result = JsonConvert.DeserializeObject<GetFormNodeByFormNoResponseDto>(query);

            return result ?? new GetFormNodeByFormNoResponseDto() { Suc = false };
        }
        catch (Exception e)
        {
            _logger.LogError(e, "获取表单节点失败");
            return new GetFormNodeByFormNoResponseDto() { Suc = false };
        }
    }
}

public interface IHttpHelper
{
    Task<GetFormNodesForInstanceResponseDto> GetFormNodesForInstance(int formId);
    Task<GetFormNodeByFormNoResponseDto> GetFormNodeByFormNo(string formNo);
}